﻿using UnityEngine;
using System.Collections;

public class playerController : MonoBehaviour {

	public GameObject player;
	public float speed = 5f;
	public GameObject hook;
	public static bool placeOne;
	private Collider2D[] results;
	public static Collider2D[] standingOn;

	public static bool gripped = false; 
	bool grounded = false;

	public Transform groundCheck;
	public LayerMask whatIsGround;
	Vector3 hookTarget;
	Vector3 destination;

	// Use this for initialization
	void Start () {
		results = new Collider2D[1];
		standingOn = new Collider2D[1];
		Physics.IgnoreLayerCollision(5,7);
		placeOne = false;
		player.GetComponent<DistanceJoint2D> ().enabled = false;
		destination = player.transform.position;

	}

	// Update is called once per frame
	void Update () {

		Physics2D.OverlapCircleNonAlloc (groundCheck.position, 0.2f, standingOn, whatIsGround);
		Vector3 playerPosition = player.transform.position;
		if (Input.GetMouseButtonDown (0) && placeOne == false) {

			Vector3 hookTarget = Camera.main.ScreenToWorldPoint(Input.mousePosition);
			Physics2D.OverlapCircleNonAlloc(hookTarget,0.5f,results);
			Vector3 direction = hookTarget - player.transform.position;
			
			if(standingOn[0]!=results[0]){//Se e jogador apontar para um local em que a persongem nao esta pisando, atira o gancho.
				GameObject clone = (GameObject)Instantiate(hook,playerPosition,Quaternion.identity);
				placeOne = true;
				//Vector3 direction = mousePosition - player.transform.position;
				float angle = Mathf.Atan2(direction.y, direction.x)* Mathf.Rad2Deg;
				clone.transform.rotation = Quaternion.AngleAxis(angle-90, Vector3.forward);
				clone.rigidbody2D.AddForce(clone.transform.up*1500);
			}
			if(standingOn[0]==results[0]){
				destination = Camera.main.ScreenToWorldPoint(Input.mousePosition);
				results[0]=null;

			}
			//player.rigidbody2D.isKinematic = true;
			//Debug.Log("player: "+playerPosition+"Mouse position: "+mousePosition);


		}
		if(gripped != true)
		player.transform.position = Vector3.MoveTowards (player.transform.position, new Vector3(destination.x,player.transform.position.y,0f), speed * Time.deltaTime);

		
	}

}
